package se.kayarr.cardplay.backend;

import lombok.Getter;

import org.mozilla.javascript.Context;
import org.mozilla.javascript.ContextFactory;
import org.mozilla.javascript.ImporterTopLevel;
import org.mozilla.javascript.Scriptable;
import org.mozilla.javascript.ScriptableObject;
import org.pircbotx.PircBotX;

import se.kayarr.cardplay.gameplay.CardManager;
import se.kayarr.cardplay.gameplay.CommandListener;
import se.kayarr.cardplay.shared.Util;

public class Initializer {
	@Getter private static ScriptableObject sharedScope;
	
	@Getter private static boolean debugMode = false;
	
	private static final String standardFuncs = "" + //TODO Put in external .js file?
			"function simpleAttackFunc(damage, type) {" +
			"	if(!type) type = Type.NEUTRAL;" +
			"	return function(ability, unit, user, target) {" +
			"		var dmg = target.dealDamage(damage, type);" +
			"		unit.session.narrate(unit.name + \" attacks \" +" +
			"			target.name + \" for \" + dmg + \" damage!\");" +
			"		return true;" +
			"	};" +
			"}";
	
	public static Scriptable newScriptScope() {
		Scriptable scope = Context.getCurrentContext().newObject(sharedScope);
		scope.setPrototype(sharedScope);
		scope.setParentScope(null);
		return scope;
	}
	
	public static Context getScriptContext() {
		return Context.getCurrentContext();
	}
	
	public static void main(String[] args) {
		for(int i = 0; i < args.length; i++) {
			switch(args[i]) {
				case "-d": case "--debug":
					debugMode = true;
					break;
				default:
					break;
			}
		}
		
		try {
			Context scriptContext = ContextFactory.getGlobal().enterContext();
			
			sharedScope = scriptContext.initStandardObjects(new ImporterTopLevel(scriptContext), true);
			
			//*
			int globalConstPropFlags =
					ScriptableObject.DONTENUM | ScriptableObject.PERMANENT | ScriptableObject.READONLY;
			sharedScope.defineFunctionProperties(new String[]{ "debug" }, Util.class, globalConstPropFlags);
			//*/
			
			scriptContext.evaluateString(sharedScope,
					"importClass(Packages.se.kayarr.cardplay.shared.Util);" +
					"importClass(Packages.se.kayarr.cardplay.gameplay.Targetable);" +
					"importClass(Packages.se.kayarr.cardplay.gameplay.Type);",
					"<internal>", 0, null);
			
			scriptContext.evaluateString(sharedScope, standardFuncs, "<internal>", 0, null);
			
			PircBotX bot = new PircBotX();
			bot.getListenerManager().addListener(new CommandListener());
			bot.setVerbose(false);
			bot.setName("CardplayBot");
			
			//*
			bot.connect("irc.esper.net", 6667);
			bot.joinChannel("#warcan");
			//*/
			
			CardManager.getInstance();
		}
		catch(Exception e) {
			e.printStackTrace();
		}
		finally {
			Context.exit();
		}
	}
}
